export const BASE_URL = import.meta.env.VITE_BASE_URL as string

export const createRequest = (options: Options = {}) => {
	options = Object.assign(
		{
			loading: true, //是否开启转圈圈，默认开启
			showSuccessMessage: false, //是否开启code为1的消息提示，默认关闭
			showErrorMessage: false, //是否开启code为0的消息提示，默认关闭
			loginStatus: true //是否开启未登录跳页
		},
		options
	)

	//请求参数增加token
	// options.data = Object.assign({
	//     token: uni.getStorageSync('token')
	// }, options.data)

	return new Promise((reslove, reject) => {
		let token = uni.getStorageSync("token")
		// if (!token && options.loginStatus) {
		//     uni.reLaunch({
		//         url: '/pages/login/login'
		//     })
		//     return
		// }

		if (options.loading) {
			uni.showLoading({
				title: "加载中"
			})
		}

		uni.request({
			url: BASE_URL + options.url,
			method: options.method ? options.method : "POST",
			data: options.data || {},
			header: {
				"Content-Type": options.contentType ? "application/json;charset=UTF-8" : "application/x-www-form-urlencoded"
				// 'token': 'assad'
			},
			dataType: "json",
			timeout: 10 * 1000,
			success: (res: any) => {
				uni.hideLoading()
				if (res.data.code == 1 && options.showErrorMessage) {
					uni.showToast({
						title: res.data.info,
						icon: "none"
					})
				}
				if (res.data.code == 0 && options.showSuccessMessage) {
					uni.showToast({
						title: res.data.info,
						icon: "none"
					})
				}

				if (res.data.code == 101) {
					//未登录
					uni.showToast({
						title: res.data.info,
						icon: "none"
					})
				}
				reslove(res.data)
			},
			fail: (err: any) => {
				uni.showToast({
					title: "服务器请求超时",
					icon: "none"
				})
				reject(err)
			}
		})
	})
}

//获取用户信息
export const getUserInfo = () => {
	return new Promise((reslove, reject) => {
		createRequest({
			url: "/user/user/get_user_info",
			method: "POST"
		}).then((res: any) => {
			reslove(res)
		})
	})
}

//上传
export const uploadFile = (url: string) => {
	return new Promise((reslove, reject) => {
		uni.uploadFile({
			url: BASE_URL + "/api/common/upload",
			filePath: url, //临时路径
			name: "file",
			header: {
				batoken: uni.getStorageSync("batoken")
			},
			success: function (res) {
				reslove(res.data)
			}
		})
	})
}

interface Options {
	//请求api路径
	url?: string
	//请求数据
	data?: any
	//请求方式
	method?: "OPTIONS" | "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "TRACE" | "CONNECT"
	//请求头
	contentType?: string
	// 是否开启取消重复请求, 默认为 true
	CancelDuplicateRequest?: boolean
	// 是否开启loading层效果, 默认为true
	loading?: boolean
	// 是否开启接口错误信息展示,默认为true 1
	showErrorMessage?: boolean
	// 是否开启接口正确信息展示,默认为true 0
	showSuccessMessage?: boolean
	// //是否开启未登录跳页
	loginStatus?: boolean
}

export interface anyObj {
	[key: string]: any
}

interface RequestConfig {
	data?: string
	url?: string
	method?: string
	header?: anyObj
}
